import {EventEmitter, Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class ProductService {

  searchEvent: EventEmitter<ProductSearchParams> = new EventEmitter();

  constructor(private http: Http) { }

  getProducts(): Observable<Product[]> {
    return this.http.get('/api/products')
      .map(res => res.json());
  }

  getProduct(id: number): Observable<Product> {
    return this.http.get('/api/product/' + id)
      .map(res => res.json());
  }

  getCommentsByProductId(id: number): Observable<Comment[]> {
    return this.http.get('/api/product/' + id + '/comments')
      .map(res => res.json());
  }

  getCategories(): string[] {
    return ['电子产品', '图书', '硬件设备'];
  }

  search(params: ProductSearchParams): Observable<Product[]> {

    let query = {};
    if (params.title !== null) {
      Object.assign(query, {'title': params.title});
    }

    if (params.price !== null) {
      Object.assign(query, {'price': params.price});
    }

    if (params.category !== null) {
      Object.assign(query, {'category': params.category});
    }

    return this.http.get('/api/products', {params: query})
      .map(res => res.json());
    // {params: this.encodeParams(params)}
  }

  private encodeParams(params: ProductSearchParams) {
    // return Object.keys(params)
    //   .filter(key => params[key])
    //   .reduce((sum: URLSearchParams, key: string) => {
    //     sum.append(key, params[key])
    //     return sum;
    //   }, new URLSearchParams());
    let query: URLSearchParams = new URLSearchParams();
    query.append('title', params.title);
    query.append('price', params.price + '');
    query.append('category', params.category);

    // result = Object.keys(params)
    //   .filter(key => params[key])
    //   .reduce((sum: URLSearchParams, key: string) => {
    //     sum.append(key, params[key]);
    //     return sum;
    //   }, new URLSearchParams());

    return query;
  }
}

export class Product {
  constructor(
    public id: number,
    public title: string,
    public price: number,
    public rating: number,
    public desc: string,
    public categories: Array<string>
  ) {

  }
}

export class Comment {
  constructor(
    public id: number,
    public productId: number,
    public timestamp: string,
    public user: string,
    public rating: number,
    public content: string
  ) {

  }
}

export class ProductSearchParams {
  constructor(
    public title: string,
    public price: number,
    public category: string
  ) {

  }
}
